<?php

/**
 * cleanUpForm actions.
 *
 * @package    WacStorehouse
 * @subpackage cleanUpForm
 * @author     JianBinBi <prince.bi@gmail.com>
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 *
 * notes:
 * if clone as another one, below tags need to be replace to ur target module tag
 * "cleanUpForm" , "CleanUpForm", "clean_up_form"
 */
class cleanUpFormActions extends WacCommonActions
{
    /**
     * get searching list
     * @package
     * @author     ben
     */
    public function executeGetList(sfWebRequest $request) {
        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $jqGridDataHelper = JqGridDataHelper::getInstance();

        $arrParam = array();
        if($jqGridDataHelper->loadComplexQuery($request)) {

            if($request->hasParameter(JqGridDataHelper::$KEY_SEARCH_FIELD) && $request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER)!="") {
                $arrParam['andWhere'] = array(
                        $jqGridDataHelper->getCondMapStr($request->getParameter(JqGridDataHelper::$KEY_SEARCH_OPER), "t1.".$request->getParameter(JqGridDataHelper::$KEY_SEARCH_FIELD), $request->getParameter(JqGridDataHelper::$KEY_SEARCH_STRING))
                );
            }

            if($request->hasParameter("status")) {
                $arrParam['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }

            if($request->hasParameter(JqGridDataHelper::$KEY_SIDX)) {
                switch($request->getParameter(JqGridDataHelper::$KEY_SIDX)) {
                    case "production_order_code":
                        $arrParam['orderBy'] = "wpo.code ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "supplier_name":
                        $arrParam['orderBy'] = "ws.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "factory_name":
                        $arrParam['orderBy'] = "wf.name ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "status_name":
                        $arrParam['orderBy'] = "t1.status ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "maker_name":
                        $arrParam['orderBy'] = "wm.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    case "auditor_name":
                        $arrParam['orderBy'] = "wa.username ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                    default:
                        $arrParam['orderBy'] = "t1.".$request->getParameter(JqGridDataHelper::$KEY_SIDX)." ".$request->getParameter(JqGridDataHelper::$KEY_SORD);
                        break;
                }
            }

            $resultSet = $this->mainModuleTable->getCustomList($arrParam, $request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false);
        }
        else {
            if($request->hasParameter("status")) {
                $arrParam['andWhere'][] = "status=".StaticWacFormStatus::getId($this->getRequest()->getParameter("status"));
            }
            $resultSet = $this->mainModuleTable->getCommonList($request->getParameter(JqGridDataHelper::$KEY_PAGE), $request->getParameter(JqGridDataHelper::$KEY_ROWS), false, $arrParam);
        }

        $filterResultSet = $this->filterList($resultSet);

        $pager = $this->mainModuleTable->getPager();
        $filterResultSet = $jqGridDataHelper->convert($filterResultSet, $pager, JsCommonData::getSuccessDatum());

        return OutputHelper::getInstance()->outputJsonOrTextFormat($filterResultSet, $this);
    }

  /*
   * override filter list
   */
  public function filterList($listObjs)
  {
      $filterArr = array();
      if(count($listObjs) > 0)
      {
          foreach($listObjs as $listObj)
          {
              $tmpArr = $listObj->toArray();
              $tmpArr['production_order_code']        = $listObj->getWacProductionOrder()->getCode();
              $tmpArr['goods_amount_unit_code_name']  = $listObj->getWacGoodsAmountUnitCode()->getName();
              $tmpArr['supplier_name']                = $listObj->getWacSupplier()->getName();
              $tmpArr['factory_name']                 = $listObj->getWacFactory()->getName();
              $tmpArr['roll_unit_code_name']          = $listObj->getWacRollUnitCode()->getName();
              $tmpArr['roll_unit_code_name']          = $listObj->getWacWrapUnitCode()->getName();
              $tmpArr['test_cloth_unit_code_name']    = $listObj->getWacTestClothUnitCode()->getName();

              $formatDate = new DateTime($listObj->getStartDate());
              $tmpArr['start_date']                   = $formatDate->format("Y-m-d");

              $formatDate = new DateTime($listObj->getDeliveryDate());
              $tmpArr['delivery_date']                = $formatDate->format("Y-m-d");

              $tmpArr['status_name']                  = StaticWacFormStatus::getCaptionById($listObj->getStatus());

              $filterArr[] = $tmpArr;
          }
      }

      return $filterArr;
  }

  /*
   * @return inspect result
   */
  public function inspectDataValidation(sfWebRequest $request, $params=array())
  {
      $result    = JsCommonData::getSuccessDatum();
      $reqParams = $request->getParameterHolder()->getAll();


      $exceptId = isset($reqParams['id']) ? $reqParams['id'] : 0;
      if($this->mainModuleTable->isExistedCode($reqParams['code'], $exceptId))
      {
         $result = JsCommonData::getErrorDatum(WacErrorCode::getInfo(WacErrorCode::$duplicatedName, $reqParams['code']), WacErrorCode::$duplicatedName);
         return $result;
      }

      if(empty($reqParams['production_order_id']) || !Doctrine::getTable(WacTable::$productionOrder)->isExistedId($reqParams['production_order_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_production_order"),  WacErrorCode::$logicError
                  );
         return $result;
      }

      if(empty($reqParams['supplier_id']) || !Doctrine::getTable(WacTable::$factory)->isExistedId($reqParams['supplier_id'])){
         $result = JsCommonData::getErrorDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_supplier"),  WacErrorCode::$logicError
                  );
         return $result;
      }

//      if(empty($reqParams['factory_id']) || !Doctrine::getTable(WacTable::$factory)->isExistedId($reqParams['factory_id'])){
//         $result = JsCommonData::getErrorDatum(
//                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invalid_factory"),  WacErrorCode::$logicError
//                  );
//         return $result;
//      }

      return $result;
  }

  /*
   * @return list data array
   */
  public function executeAdd(sfWebRequest $request)
  {
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $objProductionOrder = Doctrine::getTable(WacTable::$productionOrder)->findOneBy('id', $reqParams['production_order_id']);
          $targetItem      = $this->mainModuleTable->create();

          if(count($reqParams)>0) {
//              $targetItem->set($reqParams['']);
              $targetItem->setMakerId($this->getUser()->getGuardUser()->getId());
              $targetItem->setCurrencyCode($objProductionOrder->getCurrencyCode());

              if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['production_order_id'])) {$targetItem->setProductionOrderId($reqParams['production_order_id']);}
              if(isset($reqParams['supplier_id']))         {
                  $targetItem->setSupplierId($reqParams['supplier_id']);
                  $targetItem->setFactoryId($reqParams['supplier_id']);
               }
//              if(isset($reqParams['factory_id']))          {$targetItem->setFactoryId($reqParams['factory_id']);}
              if(isset($reqParams['start_date']))          {$targetItem->setStartDate($reqParams['start_date']);}
              if(isset($reqParams['delivery_date']))       {$targetItem->setDeliveryDate($reqParams['delivery_date']);}
              if(isset($reqParams['goods_amount_unit_code'])) {$targetItem->setGoodsAmountUnitCode($reqParams['goods_amount_unit_code']);}

              $targetItem->setIsFire(isset($reqParams['is_fire'])?1:0);
              $targetItem->setIsOnstarch(isset($reqParams['is_onstarch'])?1:0);
              $targetItem->setIsOffstarch(isset($reqParams['is_offstarch'])?1:0);
              $targetItem->setIsWater(isset($reqParams['is_water'])?1:0);
              $targetItem->setIsSilk(isset($reqParams['is_silk'])?1:0);
              $targetItem->setIsBeveled(isset($reqParams['is_beveled'])?1:0);
              $targetItem->setIsAntiShrink(isset($reqParams['is_anti_shrink'])?1:0);
              $targetItem->setIsHeatSet(isset($reqParams['is_heat_set'])?1:0);
              $targetItem->setIsShrink(isset($reqParams['is_shrink'])?1:0);
              if(isset($reqParams['texture']))             {$targetItem->setTexture($reqParams['texture']);}
//              if(isset($reqParams['texture_unit_code']))   {$targetItem->setTextureUnitCode($reqParams['texture_unit_code']);}
              if(isset($reqParams['horizontal_shrink']))   {$targetItem->setHorizontalShrink($reqParams['horizontal_shrink']);}
              if(isset($reqParams['vertical_shrink']))     {$targetItem->setVerticalShrink($reqParams['vertical_shrink']);}
              if(isset($reqParams['ph_value']))            {$targetItem->setPhValue($reqParams['ph_value']);}
              if(isset($reqParams['roll']))                {$targetItem->setRoll($reqParams['roll']);}
              if(isset($reqParams['roll_unit_code']))      {$targetItem->setRollUnitCode($reqParams['roll_unit_code']);}
              if(isset($reqParams['piece_length']))        {$targetItem->setPieceLength($reqParams['piece_length']);}
              if(isset($reqParams['wrap']))                {$targetItem->setWrap($reqParams['wrap']);}
              if(isset($reqParams['wrap_unit_code']))      {$targetItem->setWrapUnitCode($reqParams['wrap_unit_code']);}
              if(isset($reqParams['test_cloth_number']))   {$targetItem->setTestClothNumber($reqParams['test_cloth_number']);}
              if(isset($reqParams['test_cloth_unit_code'])){$targetItem->setTestClothUnitCode($reqParams['test_cloth_unit_code']);}
              
              if(isset($reqParams['memo']))                {$targetItem->setMemo($reqParams['memo']);}

              $targetItem->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$init));
              $targetItem->save();

              $this->afterAdd($request, $targetItem);

              // process production order
              $objWorkflowItem = Doctrine::getTable(WacTable::$workflowItem)->findOneBy('code', StaticWacWorkFlow::$wfClothCleanUp);
              $objProductionOrder->setCurrentWorkflowItemId($objWorkflowItem->getId());
//              $objProductionOrder->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$processing));
              $objProductionOrder->save();
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_add_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return list data array
   */
  public function executeEdit(sfWebRequest $request)
  {
      // forward to 404 if no id
      $this->forward404Unless($request->hasParameter('id'));

      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $reqParams     = $this->getRequest()->getParameterHolder()->getAll();
      $resultSet     = JsCommonData::getCommonDatum();
      $inspectResult = $this->inspectDataValidation($request);

      if($inspectResult['status'] == WacOperationStatus::$Error)
      {
          $resultSet['info'] = $inspectResult;
      }
      else
      {
          $targetItem = $this->mainModuleTable->findOneById($request->getParameter('id'));

          if(count($reqParams)>0) {
              if(isset($reqParams['code']))                {$targetItem->setCode($reqParams['code']);}
              if(isset($reqParams['production_order_id'])) {$targetItem->setProductionOrderId($reqParams['production_order_id']);}
              if(isset($reqParams['supplier_id']))         {
                  $targetItem->setSupplierId($reqParams['supplier_id']);
                  $targetItem->setFactoryId($reqParams['supplier_id']);
                  }
//              if(isset($reqParams['factory_id']))          {$targetItem->setFactoryId($reqParams['factory_id']);}
              if(isset($reqParams['start_date']))          {$targetItem->setStartDate($reqParams['start_date']);}
              if(isset($reqParams['delivery_date']))       {$targetItem->setDeliveryDate($reqParams['delivery_date']);}
              if(isset($reqParams['goods_amount_unit_code'])) {$targetItem->setGoodsAmountUnitCode($reqParams['goods_amount_unit_code']);}

              $targetItem->setIsFire(isset($reqParams['is_fire'])?1:0);
              $targetItem->setIsOnstarch(isset($reqParams['is_onstarch'])?1:0);
              $targetItem->setIsOffstarch(isset($reqParams['is_offstarch'])?1:0);
              $targetItem->setIsWater(isset($reqParams['is_water'])?1:0);
              $targetItem->setIsSilk(isset($reqParams['is_silk'])?1:0);
              $targetItem->setIsBeveled(isset($reqParams['is_beveled'])?1:0);
              $targetItem->setIsAntiShrink(isset($reqParams['is_anti_shrink'])?1:0);
              $targetItem->setIsHeatSet(isset($reqParams['is_heat_set'])?1:0);
              $targetItem->setIsShrink(isset($reqParams['is_shrink'])?1:0);
              
              if(isset($reqParams['texture']))             {$targetItem->setTexture($reqParams['texture']);}
//              if(isset($reqParams['texture_unit_code']))   {$targetItem->setTextureUnitCode($reqParams['texture_unit_code']);}
              if(isset($reqParams['horizontal_shrink']))   {$targetItem->setHorizontalShrink($reqParams['horizontal_shrink']);}
              if(isset($reqParams['vertical_shrink']))     {$targetItem->setVerticalShrink($reqParams['vertical_shrink']);}
              if(isset($reqParams['ph_value']))            {$targetItem->setPhValue($reqParams['ph_value']);}
              if(isset($reqParams['roll']))                {$targetItem->setRoll($reqParams['roll']);}
              if(isset($reqParams['roll_unit_code']))      {$targetItem->setRollUnitCode($reqParams['roll_unit_code']);}
              if(isset($reqParams['piece_length']))        {$targetItem->setPieceLength($reqParams['piece_length']);}
              if(isset($reqParams['wrap']))                {$targetItem->setWrap($reqParams['wrap']);}
              if(isset($reqParams['wrap_unit_code']))      {$targetItem->setWrapUnitCode($reqParams['wrap_unit_code']);}
              if(isset($reqParams['test_cloth_number']))   {$targetItem->setTestClothNumber($reqParams['test_cloth_number']);}
              if(isset($reqParams['test_cloth_unit_code'])){$targetItem->setTestClothUnitCode($reqParams['test_cloth_unit_code']);}

              if(isset($reqParams['memo']))                {$targetItem->setMemo($reqParams['memo']);}

              $targetItem->save();

              $this->afterEdit($request, $targetItem);
          }

          $resultSet['items'][0] = $targetItem->toArray();
          $resultSet['info']     = JsCommonData::getSuccessDatum(
                                       Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_edit_succ")
                                   );
      }

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return list data array
   */
  public function executeGetFormData(sfWebRequest $request)
  {
      if ($this->getRequest()->isXmlHttpRequest()) {
          sfConfig::set('sf_web_debug', false);
      }

      $resultSet = JsCommonData::getCommonDatum();
      $resultSet['info'] = JsCommonData::getSuccessDatum();

      $resultSet['items']['unit'] = Doctrine::getTable(WacTable::$unit)->getCodeNameHash();

      $resultSet['items']['default']['currency_code_name'] = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$currency);
      $resultSet['items']['default']['cloth_unit_code']    = Doctrine::getTable(WacTable::$systemParameter)->getValueByCode(WacAppSettingCode::$clothUnitCode);

      return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);

  }

  /*
   * @return inspect result
   */
   protected function auditValidation(sfWebRequest $request, $objCleanUpForm, $params=array()) {
       $result    = JsCommonData::getSuccessDatum();
       $reqParams = $request->getParameterHolder()->getAll();

       if($objCleanUpForm->getStatus() != StaticWacFormStatus::getId(StaticWacFormStatus::$init)) {
           $result = JsCommonData::getErrorDatum(
                   Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_status"),  WacErrorCode::$logicError
           );
           return $result;
       }

       $items = $objCleanUpForm->getWacCleanUpFormItem();
       if($items->count()==0) {
           $result = JsCommonData::getErrorDatum(
                   Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_invaild_audit_zero_item"),  WacErrorCode::$logicError
           );
           return $result;

       }

       return $result;
   }

  /*
     * @return list data array
    */
    public function executeAudit(sfWebRequest $request)
    {
        // forward to 404 if no id
        $this->forward404Unless($request->hasParameter('clean_up_form_id'));

        if ($this->getRequest()->isXmlHttpRequest()) {
            sfConfig::set('sf_web_debug', false);
        }

        $resultSet = JsCommonData::getCommonDatum();

        $objCleanUpForm = Doctrine::getTable(WacTable::$cleanUpForm)->findOneBy('id', $request->getParameter('clean_up_form_id'));
        $validationResult = $this->auditValidation($request, $objCleanUpForm);

        if($validationResult['status'] == WacOperationStatus::$Error) {
            $resultSet['info'] = $validationResult;
        }
        else
        {
            try
            {
                $objProducer = $objCleanUpForm->getWacSupplier();
                $opResultData = $objProducer->getMinusOrderItemConsumeGoods($objCleanUpForm->getWacCleanUpFormItem());
                if($opResultData["error"]) {
                    $errorMsgPtn = Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_err_goods_number_insufficient_in_factory");
                    $errorMsg = MessageHelper::getInstance()->getMsgOfMinusOrderItemConsumeGoods($opResultData, $errorMsgPtn);
                    throw new WacAppException($errorMsg, WacErrorCode::$logicError);
                }
                else {
//                    $objProducer->setMinusOrderItemConsumeGoods($opResultData);
                    $objProducer->decreaseGoods($objCleanUpForm);
                }

                $objProducer->storeGoods($objCleanUpForm);
                $objCleanUpForm->setStatus(StaticWacFormStatus::getId(StaticWacFormStatus::$audited));
                $objCleanUpForm->setAuditorId($this->getUser()->getGuardUser()->getId());
                $objCleanUpForm->setAuditorDate(format_date(time()));
                $objCleanUpForm->save();

                $resultSet['info'] = JsCommonData::getSuccessDatum(
                        Doctrine::getTable(WacTable::$sysmsg)->getContentByCode("sys_audit_succ")
                );

                $this->afterAudit($request, $objCleanUpForm);
            }
            catch (WacAppException $e) {		// catch application exception, and handle it
                $resultSet['info'] = JsCommonData::getErrorDatum($e->getMessage());
            }
            catch (Exception $e) {        // catch general exception
                WacAppException::handleGeneralError($e);
            }
            
        }

        return OutputHelper::getInstance()->outputJsonOrTextFormat($resultSet, $this);
    }


}
